package com.example.demo.util;


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

import java.io.IOException;

/**
 * @author: zyc
 */
public class PdfUtil {


    /**
     * 删除pdf中的某一页
     *
     * @param document  pdf文档对象
     * @param pageIndex 需要删除的页索引，从0开始
     * @throws IOException
     */
    public static void removePage(PDDocument document, int pageIndex) throws IOException {
        if (document.isEncrypted()) {
            throw new IOException("Encrypted documents are not supported for this example");
        }
        int numberOfPages = document.getNumberOfPages();
        if (numberOfPages <= pageIndex) {
            throw new IOException("删除的长度超出了文档的最大长度");
        }
        document.removePage(pageIndex);
    }

    /**
     * 读取指定的页的内容
     * @param document pdf文档
     * @param startIdx 读取的页索引
     * @return 页文本
     * @throws IOException
     */
    public static String readPage(PDDocument document, int startIdx) throws IOException {
        return readPage(document, startIdx, startIdx + 1);
    }

    /**
     * 读取某一页的文本数据
     *
     * @param document pdf文档对象
     * @param startIdx 开始读取的页
     * @param endIdx   结束读取的页（不包含）
     */
    public static String readPage(PDDocument document, int startIdx, int endIdx) throws IOException {
        PDFTextStripper reader = new PDFTextStripper();
        reader.setStartPage(startIdx);
        reader.setEndPage(endIdx);
        return reader.getText(document);
    }
}
